<template>
  <div class="app-container" v-if="show">
    <el-form class="ry_form" v-show="showSearch" :inline="true" label-width="100px" :model="queryParams" ref="queryForm"
      size="medium">
      <el-form-item :label="$t('instorage.status')" prop="receiptOrderStatus">
        <DictRadio v-model="queryParams.receiptOrderStatus" :radioData="dict.type.wms_receipt_status" :showAll="'all'"
          size="small" @change="handleQuery"></DictRadio>
      </el-form-item>
      <el-form-item :label="$t('instorage.type')" prop="receiptOrderType">
        <DictRadio v-model="queryParams.receiptOrderType" :radioData="dict.type.wms_receipt_type" :showAll="'all'"
          size="small" @change="handleQuery"></DictRadio>
      </el-form-item>
      <el-form-item :label="$t('instorage.No')" prop="receiptOrderNo">
        <el-input v-model="queryParams.receiptOrderNo" clearable="clearable" :placeholder="$t('common.pleaseInput')" size="small"
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item class="flex_one tr">
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row class="mb8" :gutter="10">
      <el-col :span="1.5">
        <el-button v-hasPermi="['wms:receiptOrder:add']" icon="el-icon-plus" plain="plain" size="mini" type="primary"
          @click="handleAdd()">{{ $t('instorage.newadd') }}
        </el-button>
        <!-- <el-button plain="plain" size="mini" type="primary" @click="handleImport()">导入入库单</el-button> -->
      </el-col>
      <right-toolbar :columns="columns" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <WmsTable v-loading="loading" :data="wmsReceiptOrderList" @selection-change="handleSelectionChange">
      <el-table-column v-if="columns[0].visible" align="center" :label="$t('instorage.No')" prop="receiptOrderNo"></el-table-column>
      <el-table-column v-if="columns[1].visible" align="center" :label="$t('instorage.type')">
        <template slot-scope="scope">
          <el-tag effect="plain" size="medium">
            <span v-if="scope.row.type === 'BOX'">{{ $t('instorage.BOX') }}</span>
            <span v-else>{{ $t('instorage.SKU') }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[2].visible" align="center" :label="$t('common.Warehouse/storage area')" prop="warehouseName">
        <template slot-scope="scope">
          <span>{{ scope.row.warehouseName }}<span v-if="scope.row.areaName">/{{ scope.row.areaName }}</span></span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[2].visible" align="center" :label="$t('common.CabinetNo')"  prop="cabinetNum"></el-table-column>
      <el-table-column v-if="columns[3].visible" align="center" :label="$t('common.piece')"  prop="detailCount"></el-table-column>
      <el-table-column v-if="columns[6].visible" align="center" :label="$t('instorage.status')">
        <template slot-scope="scope">
          <el-tag effect="plain" size="medium" :type="getReceiptOrderStatusTag(scope.row)">{{
            getReceiptOrderStatus(scope.row)
          }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[7].visible" align="center" :label="$t('common.remark')" prop="remark">
        <template v-slot="{ row }">
          <el-popover placement="left" width="300" trigger="hover" :content="row.remark" popper-class="popperOptions">
            <p class="showOverTooltip" slot="reference">{{ row.remark }}</p>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('common.createTime')" prop="createTime"></el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" :label="$t('common.operation')">
        <template v-slot="{ row }">
          <!-- v-if="ReceiptOrderConstant.Status.NOT_IN === row.receiptOrderStatus"  -->
          <!-- <el-button v-hasPermi="['wms:receiptOrder:edit']"
            icon="el-icon-edit" size="mini"
            type="text" @click.stop="handleUpdate(row)">{{ $t('common.edit') }}
          </el-button> -->
          <el-button v-hasPermi="['wms:receiptOrder:remove']" icon="el-icon-delete" size="mini" type="text"
            @click.stop="handleDelete(row)">{{ $t('common.del') }}
          </el-button>
          <el-button
            size="mini"
            type="text" @click="toDetail(row)">{{ $t('common.toDetail') }}
          </el-button>
          <!-- row.detailCount && row.receiptOrderStatus !== 3 && row.type !== 'BOX' -->
          <el-button v-hasPermi="['wms:receiptOrder:status']" v-if="row.detailCount && row.receiptOrderStatus !== 3"
            icon="el-icon-truck" size="mini" type="text" @click.stop="handleStatus(row)">{{ $t('instorage.Shipping') }}
          </el-button>
          <el-button icon="el-icon-print" size="mini" type="text" @click.stop="printOut(row, true)">{{ $t('common.print') }}</el-button>
        </template>
      </el-table-column>
    </WmsTable>
    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
      @pagination="getList"></pagination>
    <el-dialog :visible.sync="modalObj.show" :title="modalObj.title" :width="modalObj.width">
      <template v-if="modalObj.component === 'print-type'">
        <el-radio-group v-model="modalObj.form.value">
          <!-- <el-radio :label="1">{{ $t('common.lodopPrint') }}</el-radio> -->
          <el-radio :label="2">{{ $t('common.browserPrint') }}</el-radio>
        </el-radio-group>
      </template>
      <template v-if="modalObj.form.value === 2 || modalObj.component === 'window-print-preview'">
        <receipt-order-print :row="modalObj.form.row" ref="receiptOrderPrintRef"></receipt-order-print>
        <receipt-box-order-print :row="modalObj.form.row" ref="receiptBoxOrderPrintRef"></receipt-box-order-print>
      </template>
      <template slot="footer">
        <el-button @click=" modalObj.cancel">{{ $t('common.cancel') }}</el-button>
        <el-button @click=" modalObj.ok" type="primary">{{ $t('common.confirm') }}</el-button>
      </template>
    </el-dialog>
    <!-- 导入 -->
    <ImportFile ref="ImportFileRef" :title="$t('common.import')" :actionUrl="'/productShop/importExcel'" :params="form"
      :tempalteUrl="'https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230811/xls/8273192893b94393aa9abe1b38115322/一件代发订单导入模板.xls'" />
    <receipt-order-print :row="modalObj.form.row ? modalObj.form.row : ''" ref="receiptOrderPrintRef"></receipt-order-print>
    <receipt-box-order-print :row="modalObj.form.row ? modalObj.form.row : ''" ref="receiptBoxOrderPrintRef"></receipt-box-order-print>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {
  listWmsReceiptOrder,
  delWmsReceiptOrder,
  exportWmsReceiptOrder,
  getWmsReceiptOrder
} from '@/api/wms/receiptOrder'
import { mapGetters } from 'vuex'
import { STOCK_IN_TEMPLATE, STOCK_BOX_IN_TEMPLATE } from '@/utils/printData'
import ReceiptOrderPrint from '@/views/wms/receiptOrder/ReceiptOrderPrint'
import ReceiptBoxOrderPrint from '@/views/wms/receiptOrder/ReceiptBoxOrderPrint'
import { ReceiptOrderConstant } from "@/constant/ReceiptOrderConstant.ts";
import ImportFile from '@/components/Upload/ImportFile.vue'

export default {
  name: 'WmsReceiptOrder',
  components: { ReceiptOrderPrint, ImportFile, ReceiptBoxOrderPrint },
  dicts: ['wms_receipt_type', 'wms_receipt_status'],
  computed: {
    ReceiptOrderConstant() {
      return ReceiptOrderConstant
    },
    ...mapGetters(['supplierMap', 'warehouseMap', 'customerMap', 'areaMap', 'rackMap', 'userId']),
    receiptTypeMap() {
      let obj = this.dict.type.wms_receipt_type.map(item => [item.value, item.label])
      let map = new Map(obj)
      return map
    },
    receiptStatusMap() {
      let obj = this.dict.type.wms_receipt_status.map(item => [item.value, item.label])
      let map = new Map(obj)
      return map
    }
  },
  data() {
    return {
      show: false,
      modalObj: {
        title: this.$t('common.printMethod'),
        width: '520px',
        component: null,
        form: {
          value: null,
          row: null
        },
        ok: () => {
        },
        cancel: () => {
        }
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库单表格数据
      wmsReceiptOrderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptOrderNo: null,
        receiptOrderType: null,
        orderNo: null,
        receiptOrderStatus: null
      },
      // 表单校验
      rules: {},
      columns: [
        { key: 1, label: '入库单号', visible: true },
        { key: 2, label: '入库类型', visible: true },
        { key: 3, label: '柜号', visible: true },
        { key: 4, label: '件数', visible: true },
        { key: 5, label: '供应商', visible: true },
        { key: 6, label: '订单号', visible: true },
        { key: 7, label: '入库状态', visible: true },
        { key: 8, label: '备注', visible: true }
      ],
      form: {}
    }
  },
  async created() {
    this.show = true;
    if (this.show) {
      this.getList()
    }
  },
  methods: {
    getReceiptOrderTypeTag(row) {
      switch (row.receiptOrderType) {
        case 1:
          return 'success'
        case 2:
          return 'warning'
        case 3:
          return 'danger'
      }
    },
    getReceiptOrderStatusTag(row) {
      switch (row.receiptOrderStatus) {
        case 0:
          return 'info'
        case 1:
          return 'warning'
        case 2:
          return 'danger'
        case 3:
          return 'success'
      }
    },
    getReceiptOrderType(row) {
      return this.receiptTypeMap.get(row.receiptOrderType + '')
    },
    getReceiptOrderStatus(row) {
      return this.receiptStatusMap.get(row.receiptOrderStatus + '')
    },
    getSupplier(row, column) {
      return this.supplierMap.get(row.supplierId)
    },
    /** 查询入库单列表 */
    getList() {
      this.loading = true
      const { pageNum, pageSize } = this.queryParams
      const query = { ...this.queryParams, pageNum: undefined, pageSize: undefined }
      const pageReq = { page: pageNum - 1, size: pageSize }
      listWmsReceiptOrder(query, pageReq).then(response => {
        const { content, totalElements } = response
        content.map(x=>{
          x.createTime = dayjs(x.createTime).format('YYYY-MM-DD HH:mm:ss')
        })
        this.wmsReceiptOrderList = content
        this.total = totalElements
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/wms/receiptOrder/edit' })
    },
    // 导入入库单
    handleImport() {
      this.$refs.ImportFileRef.open()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      // 入库完成状态
      let finish
      if (row.receiptOrderStatus === 3) {
        finish = true
      }
      this.$router.push({ path: '/wms/receiptOrder/edit', query: { id, isEdit: true, isFinish: finish } })
    },
    handleStatus(row) {
      const id = row.id || this.ids
      this.$router.push({ path: '/wms/receiptOrder/status', query: { id } })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(this.$t('common.delMsg'), this.$t('common.reminder'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        const ids = row.id || this.ids
        const receiptOrderNo = row.receiptOrderNo
        this.$message({
          type: 'success',
          message: this.$t('common.succcessInfo')
        });
        return delWmsReceiptOrder(ids)
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm(this.$t('instorage.importMsg')).then(() => {
        this.exportLoading = true
        return exportWmsReceiptOrder(queryParams)
      }).then(response => {
        this.$download.download(response)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    printOut(row, print) {
      // this.modalObj = {
      //   show: true,
      //   title: this.$t('common.printMethod'),
      //   width: '520px',
      //   component: 'print-type',
      //   form: {
      //     value: 1,
      //     row
      //   },
      //   ok: () => {
      //     this.modalObj.show = false
      //     if (this.modalObj.form.value === 1) {
      //       this.doPrintOut(row, false)
      //     } else {
            this.windowPrintOut(row, print)
      //     }
      //   },
      //   cancel: () => {
      //     this.modalObj.show = false
      //   }
      // }
    },
    windowPrintOut(row, print) {
      this.getOrderDetail(row).then(res => {
        if (print) {
          this.modalObj.form.row = res
          this.$nextTick(() => {
            let NAME
            if(row.type === 'BOX') {
              NAME = 'receiptBoxOrderPrintRef'
            } else {
              NAME = 'receiptOrderPrintRef'
            }
            row.warehouseName = this.warehouseMap.get(row.warehouseId) || "-"
            this.$refs[NAME].start()
          })
          return
        }
        this.$nextTick(() => {
          this.modalObj = {
            show: true,
            title: '浏览器打印预览',
            width: '800px',
            component: 'window-print-preview',
            form: {
              value: 1,
              row,
              print
            },
            ok: () => {
              this.modalObj.show = false
            },
            cancel: () => {
              this.modalObj.show = false
            }
          }
        })
      })
    },
    doPrintOut(row, print) {
      this.getOrderDetail(row).then(result => {
        let Type
        if(row.type === 'BOX') {
          Type = STOCK_BOX_IN_TEMPLATE
        } else {
          Type = STOCK_IN_TEMPLATE
        }
        if (print) {
          this.$lodop.print(Type, [result])
        } else {
          this.$lodop.preview(Type, [result])
        }
      })
    },
    getOrderDetail(row) {
      //查询详情
      return getWmsReceiptOrder(row.id).then(response => {
        const { details, items } = response
        const map = {};
        (items || []).forEach(it => {
          map[it.id] = it
        })
        let detailList = [], totalCount = 0
        details && details.forEach(it => {
          // 判断是箱子打印还是SKU打印
          let prod
          if (it.itemId) {
            prod = map[it.itemId]
            totalCount += it.planQuantity
            let place = this.warehouseMap.get(it.warehouseId)
            if (it.areaId) {
              place += `/${this.areaMap.get(it.areaId)}`
            }
            if (it.rackId) {
              place += `/${this.rackMap.get(it.rackId)}`
            }
            detailList.push({
              itemName: prod.itemName,
              itemNo: prod.itemNo,
              itemType: prod.itemType,
              planQuantity: it.planQuantity,
              place
            })
          } else {
            prod = map[it.itemList]
            detailList = details.map(r=>{
              r.warehouseName = this.warehouseMap.get(r.place[0]) || "-"
              this.warehouseName = r.warehouseName
              return r
            })
          }
        })
        return {
          warehouseName: this.warehouseName,
          remark: row.remark,
          receiptOrderNo: row.receiptOrderNo,
          orderNo: row.orderNo,
          receiptType: this.receiptTypeMap.get(row.receiptOrderType + ''),
          customerName: this.customerMap.get(row.customerId) || '-',
          createTime: row.createTime,
          details: detailList,
          totalCount,
          createByName: row.createByName,
          type: row.type
        }
      })
    },
    toDetail(row) {
      const id = row.id || this.ids
      this.$router.push({ path: '/wms/receiptOrderDetail', query: { id, isEdit: false } })
    }
  }
}
</script>
<style lang="stylus">
.showOverTooltip {
  display: -webkit-box;
  text-overflow: ellipsis;
  overflow: hidden;
  /*这里是3行*/
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.popperOptions[x-placement^=left] .popper__arrow::after {
  border-left-color: #565D6B;
}

.popperOptions[x-placement^=right] .popper__arrow::after {
  border-right-color: #565D6B;
}

.popperOptions[x-placement^=bottom] .popper__arrow::after {
  border-bottom-color: #565D6B;
}

.popperOptions[x-placement^=top] .popper__arrow::after {
  border-top-color: #565D6B;
}

.popperOptions {
  background-color: #565D6B;
  color: #FFFFFF;
  border: #565D6B;
}
</style>
